package com.jappyframework;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

/**
 * A utility class to properly measure Wall-clock and CPU-time.
 * 
 * @author harsh
 *
 */
public class Timer {

	private long cpuStart;
	private long cpuEnd;
	private long userStart;
	private long userEnd;
	
	private final ThreadMXBean threadBean;

	public Timer() {
		threadBean = ManagementFactory.getThreadMXBean();
		if (threadBean.isCurrentThreadCpuTimeSupported()) {
			threadBean.setThreadCpuTimeEnabled(true);
		}
		cpuStart = Long.MAX_VALUE;
		userStart = Long.MAX_VALUE;
	}

	public void start() {
		if (threadBean.isCurrentThreadCpuTimeSupported()) {
			cpuStart = threadBean.getCurrentThreadCpuTime();
		}
		userStart = System.nanoTime();
	}
	
	public void end() {
		if (threadBean.isCurrentThreadCpuTimeSupported()) {
			cpuEnd = threadBean.getCurrentThreadCpuTime();
		}
		userEnd = System.nanoTime();
	}
	
	public long cpuNanoSeconds() {
		return (cpuEnd - cpuStart);
	}
	
	public long userNanoSeconds() {
		return (userEnd - userStart);
	}
	
	@Override
	public String toString() {
		return ("USER:-  " + userNanoSeconds() + "\t CPU:- " + cpuNanoSeconds());
	}
	
}
